'''
Author: Leo.wang wanglizhigs@163.com
Date: 2025-09-05 20:36:08
LastEditors: Leo.wang wanglizhigs@163.com
LastEditTime: 2025-09-05 21:12:12
FilePath: /medical-companion-server-python/app/order/models.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from django.db import models

from app.user.models import McUser
from app.patient.models import McPatient
from app.service.models import McService
from app.gender.models import McGender
from app.order_status.models import McOrderStatus
import datetime
import uuid


def generate_order_no():
    """
    生成32位唯一订单号：
    前17位：年月日时分秒+毫秒（YYYYMMDDHHMMSSmmm）
    后15位：UUID 随机串
    """
    now = datetime.datetime.now()
    millis = int(now.microsecond / 1000)
    date_str = now.strftime('%Y%m%d%H%M%S') + f"{millis:03d}"  # 17位时间戳
    random_str = uuid.uuid4().hex[:15]  # 15位随机字符串
    return f"YK_{date_str}"  # 共20位
    
class McOrder(models.Model):
    order_no = models.CharField(
        max_length=32,
        unique=True,
        editable=False,
        default=generate_order_no,
        verbose_name="订单号"
    )

    # 关键：设为外键，并指定使用同名列
    user = models.ForeignKey(
        McUser,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        db_column="user_id",
    )

    # patient_id = models.BigIntegerField()
    # 关键：设为外键，并指定使用同名列
    patient = models.ForeignKey(
        McPatient,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        db_column="patient_id",
    )

    # service_id = models.BigIntegerField()
    # 关键：设为外键，并指定使用同名列
    service = models.ForeignKey(
        McService,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        db_column="service_id",
    )

    amount = models.DecimalField(max_digits=10, decimal_places=0)
    start_time = models.DateTimeField()
    hospital = models.CharField(max_length=200)
    department = models.CharField(max_length=100)
    note = models.TextField(null=True, blank=True)


    # companion_gender = models.IntegerField(null=True, blank=True)
    # 关键：设为外键，并指定使用同名列
    companion_gender = models.ForeignKey(
        McGender,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        db_column="companion_gender_id",
    )

    service_duration = models.PositiveIntegerField(null=True, blank=True)
  
     # 关键：设为外键，并指定使用同名列
    status = models.ForeignKey(
        McOrderStatus,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        db_column="status_id",
    )
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'mc_order'
        verbose_name = '订单'
        verbose_name_plural = '订单'
